document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('submitForm');
    const submitBtn = document.getElementById('submitBtn');
    const btnText = submitBtn.querySelector('.btn-text');
    const loadingSpinner = submitBtn.querySelector('.loading-spinner');

    // 表单验证规则
    const validationRules = {
        name: {
            required: true,
            minLength: 2,
            maxLength: 50,
            pattern: /^[\u4e00-\u9fa5a-zA-Z\s]+$/
        },
        phone: {
            required: true,
            pattern: /^1[3-9]\d{9}$/
        },
        email: {
            required: false,
            pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/
        },
        message: {
            required: true,
            minLength: 10,
            maxLength: 500
        }
    };

    // 错误消息
    const errorMessages = {
        name: {
            required: '请输入姓名',
            minLength: '姓名至少需要2个字符',
            maxLength: '姓名不能超过50个字符',
            pattern: '请输入有效的姓名（仅支持中文、英文和空格）'
        },
        phone: {
            required: '请输入手机号码',
            pattern: '请输入有效的手机号码'
        },
        email: {
            pattern: '请输入有效的邮箱地址'
        },
        message: {
            required: '请输入留言内容',
            minLength: '留言内容至少需要10个字符',
            maxLength: '留言内容不能超过500个字符'
        }
    };

    // 验证单个字段
    function validateField(fieldName, value) {
        const rules = validationRules[fieldName];
        if (!rules) return { isValid: true };

        // 必填验证
        if (rules.required && (!value || value.trim() === '')) {
            return {
                isValid: false,
                message: errorMessages[fieldName].required
            };
        }

        // 如果字段为空且不是必填，则跳过其他验证
        if (!value || value.trim() === '') {
            return { isValid: true };
        }

        // 最小长度验证
        if (rules.minLength && value.length < rules.minLength) {
            return {
                isValid: false,
                message: errorMessages[fieldName].minLength
            };
        }

        // 最大长度验证
        if (rules.maxLength && value.length > rules.maxLength) {
            return {
                isValid: false,
                message: errorMessages[fieldName].maxLength
            };
        }

        // 正则表达式验证
        if (rules.pattern && !rules.pattern.test(value)) {
            return {
                isValid: false,
                message: errorMessages[fieldName].pattern
            };
        }

        return { isValid: true };
    }

    // 显示错误消息
    function showError(field, message) {
        const formGroup = field.closest('.form-group');
        formGroup.classList.add('error');
        
        // 移除现有的错误消息
        const existingError = formGroup.querySelector('.error-message');
        if (existingError) {
            existingError.remove();
        }
        
        // 添加新的错误消息
        const errorElement = document.createElement('div');
        errorElement.className = 'error-message';
        errorElement.textContent = message;
        formGroup.appendChild(errorElement);
    }

    // 清除错误消息
    function clearError(field) {
        const formGroup = field.closest('.form-group');
        formGroup.classList.remove('error');
        
        const errorElement = formGroup.querySelector('.error-message');
        if (errorElement) {
            errorElement.remove();
        }
    }

    // 实时验证
    function setupRealTimeValidation() {
        const fields = form.querySelectorAll('input, textarea, select');
        
        fields.forEach(field => {
            field.addEventListener('blur', function() {
                const fieldName = this.name;
                const value = this.value;
                const validation = validateField(fieldName, value);
                
                if (!validation.isValid) {
                    showError(this, validation.message);
                } else {
                    clearError(this);
                }
            });

            field.addEventListener('input', function() {
                // 如果字段有错误，在用户输入时清除错误
                if (this.closest('.form-group').classList.contains('error')) {
                    clearError(this);
                }
            });
        });
    }

    // 验证整个表单
    function validateForm() {
        let isValid = true;
        const fields = form.querySelectorAll('input, textarea, select');
        
        fields.forEach(field => {
            const fieldName = field.name;
            const value = field.value;
            const validation = validateField(fieldName, value);
            
            if (!validation.isValid) {
                showError(field, validation.message);
                isValid = false;
            } else {
                clearError(field);
            }
        });

        return isValid;
    }

    // 显示成功消息
    function showSuccessMessage() {
        const successDiv = document.createElement('div');
        successDiv.className = 'success-message';
        successDiv.innerHTML = `
            <div style="
                background: #d4edda;
                color: #155724;
                padding: 16px;
                border-radius: 8px;
                margin-top: 20px;
                text-align: center;
                border: 1px solid #c3e6cb;
            ">
                <strong>提交成功！</strong><br>
                感谢您的留言，我们会尽快与您联系。
            </div>
        `;
        
        form.appendChild(successDiv);
        
        // 3秒后移除成功消息
        setTimeout(() => {
            successDiv.remove();
        }, 3000);
    }

    // 处理表单提交
    form.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        // 验证表单
        if (!validateForm()) {
            return;
        }

        // 检查同意条款
        const agreeCheckbox = document.getElementById('agree');
        if (!agreeCheckbox.checked) {
            showError(agreeCheckbox, '请同意服务条款和隐私政策');
            return;
        }

        // 显示加载状态
        submitBtn.disabled = true;
        btnText.style.display = 'none';
        loadingSpinner.style.display = 'block';

        try {
            // 收集表单数据
            const formData = new FormData(form);
            const data = Object.fromEntries(formData.entries());
            
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 2000));
            
            // 这里可以替换为实际的API调用
            console.log('提交的数据:', data);
            
            // 显示成功消息
            showSuccessMessage();
            
            // 重置表单
            form.reset();
            
        } catch (error) {
            console.error('提交失败:', error);
            alert('提交失败，请稍后重试');
        } finally {
            // 恢复按钮状态
            submitBtn.disabled = false;
            btnText.style.display = 'block';
            loadingSpinner.style.display = 'none';
        }
    });

    // 设置实时验证
    setupRealTimeValidation();

    // 添加一些交互效果
    const inputs = form.querySelectorAll('input, textarea, select');
    inputs.forEach(input => {
        input.addEventListener('focus', function() {
            this.closest('.form-group').style.transform = 'scale(1.02)';
        });
        
        input.addEventListener('blur', function() {
            this.closest('.form-group').style.transform = 'scale(1)';
        });
    });

    // 添加键盘快捷键支持
    document.addEventListener('keydown', function(e) {
        if (e.ctrlKey && e.key === 'Enter') {
            form.dispatchEvent(new Event('submit'));
        }
    });
}); 